package xy.donate.android.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback
import com.hjq.http.listener.OnHttpListener
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.android.synthetic.main.fragment_openeye.*
import xy.donate.android.R
import xy.donate.android.common.MyFragment
import xy.donate.android.helper.TimeUtils
import xy.donate.android.http.model.HttpData
import xy.donate.android.http.request.DailyApi
import xy.donate.android.openeye.*
import xy.donate.android.openeye.Item.Companion.TYPE_ONE
import xy.donate.android.openeye.Item.Companion.TYPE_THREE
import xy.donate.android.openeye.Item.Companion.TYPE_TWO
import xy.donate.android.ui.activity.HomeActivity
import xy.donate.android.ui.activity.OpenEyeDetailActivity
import java.lang.Exception

/**
 * describe
 *
 * @author XY
 * @version V1.0
 */
class OpenEyeFragment : MyFragment<HomeActivity>(),OnRefreshListener{

    companion object{
        fun newInstance():OpenEyeFragment{
            return OpenEyeFragment()
        }
    }

    private var dateString = ""
    private var isRefresh = false
    var list = mutableListOf<Item>()
    private lateinit var myAdapter: MyAdapter

    override fun initView() {
        activity?.let {
            swipeRefreshLayoutOpenEye.setOnRefreshListener(this)
            swipeRefreshLayoutOpenEye.setEnableLoadMore(false)
//            swipeRefreshLayoutOpenEye.setColorSchemeColors(
//                ContextCompat.getColor(
//                    it,
//                    R.color.colorPrimary
//                )
//            )
        }

        fabBack.hide()
        fabBack.setOnClickListener {
            recycleViewOpenEye.smoothScrollToPosition(0)
        }

        var linearLayoutManager = LinearLayoutManager(activity,LinearLayoutManager.VERTICAL,false)
        recycleViewOpenEye.layoutManager = linearLayoutManager
        myAdapter = MyAdapter(list)
        recycleViewOpenEye.adapter = myAdapter

        recycleViewOpenEye.run {
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (linearLayoutManager.findLastVisibleItemPosition() > 10) {
                        fabBack.show()
                    } else {
                        fabBack.hide()
                    }
                }
            })
        }
        myAdapter.loadMoreModule.apply {
            setOnLoadMoreListener {
                if (TextUtils.isEmpty(dateString)) {
                    loadMoreComplete()
                    loadMoreEnd()
                } else {
                    loadMore(false)
                }
            }
        }

        myAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                activity?.let {
                    when (myAdapter.data[position].itemType) {
                        2 -> {
                            val item = adapter.data[position] as Item
                            val intent = Intent(activity, OpenEyeDetailActivity::class.java)
                            val openEyeCusBean = OpenEyeCusBean(
                                item.data.content.data.title,
                                item.data.content.data.description,
                                item.data.content.data.playUrl,
                                "" + item.data.content.data.id,
                                "" + item.data.content.data.cover.homepage,
                                item.data.content.data.category
                            )
                            intent.putExtra("openEyeCusBean", openEyeCusBean)
                            startActivity(intent)
                        }
                        3 -> {
//                            var list = mutableListOf<PhotoModel>()
//                            var photoModel = PhotoModel()
//                            var item =  adapter.data[position] as Item
//                            photoModel.originalPath = item.data.content.data.url
//                            list.add(photoModel)
//                            ImagePickerInstance.getInstance().photoPreview(activity,list,0,true)
                        }
                    }
                }
            }
        }
    }

    override fun initData() {
        loadMore(true)
    }

    class MyAdapter(data: MutableList<Item>?) :
        BaseMultiItemQuickAdapter<Item, BaseViewHolder>(data),LoadMoreModule {
        init {
            addItemType(TYPE_ONE,R.layout.item_textcard_fragment_openeye)
            addItemType(TYPE_TWO,R.layout.item_followcard_fragment_openeye)
            addItemType(TYPE_THREE,R.layout.item_picturefollowcard_fragment_openeye)
        }

        @SuppressLint("SetTextI18n")
        override fun convert(holder: BaseViewHolder, item: Item) {
            when(item.itemType){
                TYPE_ONE ->{
                    val tvOpenEyeTitleName = holder.getView<TextView>(R.id.tvOpenEyeTitleName)
                    tvOpenEyeTitleName.text = item.data.text
                    if(item.data.text == "今日社区精选"){
                        tvOpenEyeTitleName.visibility = View.GONE
                    }else{
                        tvOpenEyeTitleName.visibility = View.VISIBLE
                    }
                }
                TYPE_TWO ->{
                    val ivOpenEyeCoverImage = holder.getView<ImageView>(R.id.ivOpenEyeCoverImage)
                    val tvOpenEyeDuration = holder.getView<TextView>(R.id.tvOpenEyeDuration)
                    val tvOpenEyeTitle = holder.getView<TextView>(R.id.tvOpenEyeTitle)
                    val ivOpenEyeAuthorIcon = holder.getView<ImageView>(R.id.ivOpenEyeAuthorIcon)
                    val tvOpenEyeAuthorName = holder.getView<TextView>(R.id.tvOpenEyeAuthorName)
                    val tvOpenEyeCategoryName = holder.getView<TextView>(R.id.tvOpenEyeCategoryName)

                    Glide.with(ivOpenEyeCoverImage)
                            .load(item.data.content.data.cover.feed)
                            .apply(RequestOptions.bitmapTransform(RoundedCorners(20)))
                            .into(ivOpenEyeCoverImage)
                    tvOpenEyeDuration.text =
                        TimeUtils.convertMinAndSec(item.data.content.data.duration)
                    tvOpenEyeTitle.text = item.data.content.data.title
                    Glide.with(ivOpenEyeAuthorIcon)
                            .load(item.data.content.data.author.icon)
                            .placeholder(R.drawable.common_shape_image_default_bg)
                            .error(R.drawable.common_shape_image_default_bg)
                            .into(ivOpenEyeAuthorIcon)
                    tvOpenEyeAuthorName.text = item.data.content.data.author.name
                    tvOpenEyeCategoryName.text = " #${item.data.content.data.category}"
                }
                else ->{
                    var tvOpenEyePic = holder.getView<ImageView>(R.id.tvOpenEyePic)
                    Glide.with(tvOpenEyePic)
                            .load(item.data.content.data.url)
                            .placeholder(R.drawable.common_shape_image_default_bg)
                            .error(R.drawable.common_shape_image_default_bg)
                            .into(tvOpenEyePic)
                }
            }
        }
    }

    fun getOpenEyeDailyShow(data: OpenEyeDailyBean) {
        myAdapter.loadMoreModule.loadMoreComplete()
        if( data.nextPageUrl.contains("date")){
            val url = data.nextPageUrl
            dateString =  url.substring(url.indexOf("&")-13, url.indexOf("&"))
        }
        if(data.itemList.isNotEmpty()){
            list = data.itemList as MutableList<Item>
            for(item in list){
                when(item.type){
                    "textCard" ->{
                        item.itemType = TYPE_ONE
                    }
                    "followCard" ->{
                        item.itemType = TYPE_TWO
                    }
                    else ->{
                        item.itemType = TYPE_THREE
                    }
                }
            }
            if(isRefresh){
                myAdapter.setNewInstance(list)
            }else{
                myAdapter.addData(list)
            }
            hideDialog()
        }else{
            hideDialog()
            myAdapter.loadMoreModule.loadMoreEnd()
        }
    }

    private fun loadMore(isRefresh: Boolean) {
        this.isRefresh = isRefresh
        if(isRefresh){
            dateString = ""
            activity?.let {
                showDialog()
            }
        }
        EasyHttp.get(this)
                .api(DailyApi().setDate(dateString))
                .request((object :OnHttpListener<OpenEyeDailyBean>{
                    override fun onSucceed(result: OpenEyeDailyBean?) {
                        getOpenEyeDailyShow(result!!)
                    }

                    override fun onFail(e: Exception?) {
                        toast(e?.message)
                        hideDialog()
                        myAdapter.loadMoreModule.loadMoreFail()
                    }
                }))
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_openeye
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        loadMore(true)
    }
}